package seatiger.tomcat.catalina;

import java.util.List;

/**
 * 生命周期接口
 */
public interface Lifecycle {

    //定义启动事件的类型
    String START_EVENT = "start";
    String BEFORE_START_EVENT = "before_start";
    String AFTER_START_EVENT = "after_start";

    //定义停止事件的类型
    String STOP_EVENT = "stop";
    String BEFORE_STOP_EVENT = "before_stop";
    String AFTER_STOP_EVENT = "after_stop";

    /**
     * 添加事件监听器
     * @param listener
     */
    void addLifecycleListener(LifecycleListener listener);

    /**
     * 返回事件触发器
     * @return
     */
    List<LifecycleListener> findLifecycleListeners();

    /**
     * 移除
     * @param listener
     */
    void removeLifecycleListener(LifecycleListener listener);

    /**
     * 组件启动
     * @throws LifecycleException
     */
    void start() throws LifecycleException;

    /**
     * 组件停止
     * @throws LifecycleException
     */
    void stop() throws LifecycleException;

    /**
     * 启动组件
     * @param objs
     * @throws LifecycleException
     */
    default void startComponents(Object... objs) throws LifecycleException{
        if (objs != null && objs.length > 0){
            for (Object obj : objs){
                if(obj != null && obj instanceof Lifecycle){
                    ((Lifecycle) obj).start();
                }
            }
        }
    }

    /**
     * 停止组件
     * @param objs
     * @throws LifecycleException
     */
    default void stopComponents(Object... objs) throws LifecycleException{
        if (objs != null && objs.length > 0){
            for (Object obj : objs){
                if(obj != null && obj instanceof Lifecycle){
                    ((Lifecycle) obj).stop();
                }
            }
        }
    }
}
